using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace SumerCoreDevOps.Infrastructure.Utilities;

/// <summary>
/// 端口检测工具
/// </summary>
public static class PortUtility
{
    /// <summary>
    /// 检查端口是否可用（未被占用）
    /// </summary>
    public static bool IsPortAvailable(int port)
    {
        if (port < 1 || port > 65535)
        {
            return false;
        }

        try
        {
            // 检查 TCP 端口
            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();

            if (tcpListeners.Any(endpoint => endpoint.Port == port))
            {
                return false;
            }

            // 检查 TCP 连接
            var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
            if (tcpConnections.Any(conn => conn.LocalEndPoint.Port == port))
            {
                return false;
            }

            // 尝试绑定端口以确认可用性
            try
            {
                using var listener = new TcpListener(IPAddress.Any, port);
                listener.Start();
                listener.Stop();
                return true;
            }
            catch (SocketException)
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 批量检查端口是否可用
    /// </summary>
    public static Dictionary<int, bool> CheckPorts(params int[] ports)
    {
        var result = new Dictionary<int, bool>();
        foreach (var port in ports)
        {
            result[port] = IsPortAvailable(port);
        }
        return result;
    }

    /// <summary>
    /// 获取指定范围内的可用端口
    /// </summary>
    public static List<int> FindAvailablePorts(int startPort, int endPort, int count = 1)
    {
        var availablePorts = new List<int>();

        for (int port = startPort; port <= endPort && availablePorts.Count < count; port++)
        {
            if (IsPortAvailable(port))
            {
                availablePorts.Add(port);
            }
        }

        return availablePorts;
    }

    /// <summary>
    /// 验证端口号是否在有效范围内
    /// </summary>
    public static bool IsValidPort(int port)
    {
        return port >= 1 && port <= 65535;
    }

    /// <summary>
    /// 验证端口号是否在推荐范围内（1024-65535，避免系统保留端口）
    /// </summary>
    public static bool IsRecommendedPort(int port)
    {
        return port >= 1024 && port <= 65535;
    }

    /// <summary>
    /// 获取占用指定端口的进程信息
    /// </summary>
    public static string GetPortOwner(int port)
    {
        try
        {
            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();

            var endpoint = tcpListeners.FirstOrDefault(e => e.Port == port);
            if (endpoint != null)
            {
                return $"端口 {port} 被占用 (TCP Listener)";
            }

            var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
            var connection = tcpConnections.FirstOrDefault(c => c.LocalEndPoint.Port == port);
            if (connection != null)
            {
                return $"端口 {port} 被占用 (TCP Connection: {connection.State})";
            }

            return $"端口 {port} 未被占用";
        }
        catch (Exception ex)
        {
            return $"无法检测端口 {port}: {ex.Message}";
        }
    }
}
